//
//  MerchandiseManagerController.m
//  ios-supplier
//
//  Created by feynmanyuan on 15/4/16.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "MerchandiseManageController.h"
#import "JFBMerchandiseCategoryDS.h"
#import "MerchandiseListController.h"
#import "MerchandiseEditController.h"
#import "JFBMerchandiseCategoryDS.h"
#import "JFBLoadingAnimation.h"
#import "ZBarSDK.h"

@interface MerchandiseManageController () <ZBarReaderDelegate, JFBDataSourceRefreshDelegate,UIGestureRecognizerDelegate>{
    JFBMerchandiseCategoryDS *_currentMerchandiseCategory;
    JFBMerchandiseDS * _currentMerchandise;
}
@property (nonatomic, strong) NSMutableArray *items;
- (IBAction)scanAction:(id)sender;
@property (nonatomic, strong) JFBPager * pager;
@end

@implementation MerchandiseManageController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIView *tableHeadrView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 10)];
    [tableHeadrView setBackgroundColor:PanelBgColorDefault];
    
    self.tableView.tableHeaderView = tableHeadrView;
    
    self.items = [@[] mutableCopy];
    self.pager = [[JFBPager alloc] init];
    
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.navigationItem setLeftBarButtonItem: [self createBackView]];
}
- (void) viewWillAppear:(BOOL)animated{
    [self reload:nil];
    self.navigationItem.title = [[NSUserDefaults standardUserDefaults]objectForKey:@"categoryName"];
}

- (UIBarButtonItem *)createBackView
{
    UIButton *leftButtonItem = [UIButton buttonWithType:UIButtonTypeCustom];
    
    leftButtonItem.frame = CGRectMake(0, 0, 11, 20);
    
    [leftButtonItem setBackgroundImage:[UIImage imageNamed:@"icon-Back"] forState:UIControlStateNormal];
    
    [leftButtonItem setImageEdgeInsets: UIEdgeInsetsMake((19 - 11) / 2, 0, (19 - 11) / 2, 0)];
    
    [leftButtonItem addTarget:self action:@selector(leftButtonItemClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:leftButtonItem];
    
    return item;
}

-(void)leftButtonItemClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)reload:(__unused id)sender {
    JFBLoadingAnimation * animation = [[JFBLoadingAnimation alloc] init:self.tableView];
    [JFBMerchandiseCategoryDS loadMerchandiseCategoryList:^(NSArray *categoryList, NSError *error) {
        if (!error) {
            self.items = [categoryList mutableCopy];
            [animation stop];
            [self.tableView reloadData];
        }
    } pager:self.pager];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [self.items count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MerchandiseCategoryIdentifier" forIndexPath:indexPath];
    JFBMerchandiseCategoryDS *ds = self.items[indexPath.row];
    cell.textLabel.text = ds.categoryName;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%lu/%lu", (unsigned long)ds.shelvesNum, (unsigned long)ds.total];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)viewDidLayoutSubviews
{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)reload {
    [self reload:nil];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    _currentMerchandiseCategory = self.items[indexPath.row];
    
    [self performSegueWithIdentifier:@"merchandiseListIdentifier" sender:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if( [segue.identifier isEqualToString:@"merchandiseListIdentifier"] ) {
        MerchandiseListController * controller = (MerchandiseListController*)segue.destinationViewController;
        controller.hidesBottomBarWhenPushed = true;
        controller.merchandiseCategory = _currentMerchandiseCategory;
        controller.delegate = self;
    } else if( [segue.identifier isEqualToString:@"merchandiseDetailIdentifier"] ) {
        MerchandiseEditController * controller = (MerchandiseEditController*)segue.destinationViewController;
        controller.merchandise = _currentMerchandise;
        controller.delegate = self;
        ((UIViewController*)segue.destinationViewController).hidesBottomBarWhenPushed = true;
    } else {
        ((UIViewController*)segue.destinationViewController).hidesBottomBarWhenPushed = true;
    }
}

- (void) viewDidDisappear:(BOOL)animated
{
    self.hidesBottomBarWhenPushed = NO;
}



- (void) imagePickerController: (UIImagePickerController*) reader
 didFinishPickingMediaWithInfo: (NSDictionary*) info
{
    
    NSLog(@"info=%@",info);
    // 得到条形码结果
    id<NSFastEnumeration> results =
    [info objectForKey: ZBarReaderControllerResults];
    ZBarSymbol *symbol = nil;
    for(symbol in results)
        // EXAMPLE: just grab the first barcode
        break;
    
//    [JFBUIAnimation alertTips:symbol.data];
    [reader dismissViewControllerAnimated:YES completion:nil];
    [JFBMerchandiseDS scanQuery:^(JFBMerchandiseDS *merchandise, NSError *error) {
        if( merchandise == nil ) {
            [JFBUIAnimation topTips:self.view tipString:@"没有找到相应商品" delegate:nil];
        } else {
            _currentMerchandise = merchandise;
            [self performSegueWithIdentifier:@"merchandiseDetailIdentifier" sender:self];
        }
    } code:symbol.data];
}

- (IBAction)scanAction:(id)sender {
    
//    ZBarReaderViewController *reader = [ZBarReaderViewController new];
//    reader.readerDelegate = self;
//    reader.supportedOrientationsMask = ZBarOrientationMaskAll;
//    
//    ZBarImageScanner *scanner = reader.scanner;
//    [scanner setSymbology: ZBAR_I25
//                   config: ZBAR_CFG_ENABLE
//                       to: 0];
//    [self presentViewController:reader animated:YES completion:nil];
//    
    [self.navigationController popViewControllerAnimated:YES];
    
    
    
    
}
@end
